<?php

namespace app\common\model;

use think\facade\Cookie;
use think\Model;

class ManageModel extends Model
{
    protected $pk = 'manage_id'; //主键
    protected $autoWriteTimestamp = true; //自动时间
    // 定义时间戳字段名
    protected $createTime = 'manage_create_time';
    protected $updateTime = 'manage_update_time';

    protected $insert = ['manage_password' => '123456']; //初始密码

    // 修改器 password 字段(加密)
    public function setManagePasswordAttr($value)
    {
        return password_hash($value, PASSWORD_DEFAULT);
    }

    // 修改器 时间转数字
    public function setManageLastTimeAttr($value)
    {
        return strtotime($value);
    }

    // 获取器 login_time 登录时间
    public function getManageLoginTimeAttr($value)
    {
        return $value > 0 ? date('Y-m-d H:i:s', $value) : '—';
    }

    // 获取器 last_time 登录时间
    public function getManageLastTimeAttr($value)
    {
        return $value > 0 ? date('Y-m-d H:i:s', $value) : '—';
    }

    // 获取器 status_html 新添加字段
    public function getManageStatusHtmlAttr($value, $data)
    {
        $value = $data['manage_status'];
        $status = [
            -1 => '<label class="label label-danger label-badge">删除</label>',
            0 => '<label class="label label-warning label-badge">禁用</label>',
            1 => '<label class="label label-success label-badge">正常</label>',
            2 => '<label class="label label-info label-badge">待审核</label>',
        ];
        return isset($status[$value]) ? $status[$value] : '';
    }

    // 模型事件
    protected static function init()
    {
        // 删除前 判断是否超级管理员
        self::beforeDelete(function ($manage) {
            // 禁止删除超级管理员
            if (superman()) {
                return false;
            }
        });
    }

    /**
     * 验证密码
     * @param  [type] $password   [密码]
     * @param  [type] $ciphertext [密文]
     * @return [type]             [description]
     */
    public static function do_verify($password, $ciphertext)
    {
        return password_verify($password, $ciphertext);
    }

    /**
     * 用户登录
     * @param  [type] $username [帐号]
     * @param  [type] $password [密码]
     * @return [type]           [description]
     */
    public function do_login($username, $password)
    {
        if ($username == '') {
            $this->error = '提示：帐号不能为空!';
            return false;
        }
        // 帐号查询
        $result = $this->where('manage_username|manage_phone|manage_email', '=', $username)->find();
        if (!$result) {
            $this->error = '提示：帐号不存在!';
            return false;
        }
        // 帐号状态
        if ($result->manage_status != 1) {
            $msg = [
                '-1' => '提示：帐号不存在!(code=-1)',
                '0' => '提示：帐号被禁用!(code=0)',
                '2' => '提示：帐号待审核!(code=2)',
            ];
            $this->error = $msg[$result->manage_status];
            return false;
        }
        if (!self::do_verify($password, $result->manage_password)) {
            $this->error = '提示：密码不正确!';
            return false;
        }

        // 更新用户信息
        $result->manage_login_num = $result->manage_login_num + 1;
        $result->manage_last_time = $result->manage_login_time;
        $result->manage_login_time = time();
        $result->manage_login_ip = request()->ip();
        $result->save();

        unset($result->manage_password);
        unset($result->group->group_action);
        unset($result->group->group_create_time);
        unset($result->group->group_update_time);
        $result = $result->toArray();

        // 设置 cookie
        cookie('admin_manage', $result);

        return true;
    }

    /**
     * [do_info_save ]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function do_info_save($data)
    {
        $result = $this->where('manage_id', '=', $data['manage_id'])->find();
        if (!$result) {
            $this->error = '提示：帐号不存在';
            return false;
        }

        // 更新资料
        $result->manage_fullname = $data['manage_fullname'];
        $result->manage_phone = $data['manage_phone'];
        $result->manage_email = $data['manage_email'];
        $result->save();

        unset($result->manage_password);
        unset($result->group->group_action);
        unset($result->group->group_create_time);
        unset($result->group->group_update_time);
        $result = $result->toArray();

        // 设置 cookie
        cookie('admin_manage', $result);

        return true;
    }

    /**
     * [do_pwd_save 修改密码]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function do_pwd_save($password, $new_password)
    {
        $manage = cookie('admin_manage');
        $result = $this->where('manage_id', '=', $manage['manage_id'])->find();
        if (!$result) {
            $this->error = '提示：帐号不存在!';
            return false;
        }
        if (!self::do_verify($password, $result->manage_password)) {
            $this->error = '提示：原始密码不正确!';
            return false;
        }
        $result->manage_password = $new_password;
        $result->save();
        return true;
    }

    /**
     * [do_forget 重置密码]
     * @param  [type] $username [手机/邮箱]
     * @return [type]           [description]
     */
    public function do_forget($username)
    {

    }

    // 模型关联
    public function group()
    {
        return $this->hasOne('ManageGroupModel', 'group_id', 'manage_groupid')->bind('group_id,group_name');
    }
}
